package admin.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Category;

import models.CategoryModel;

import admin.data.CategoryData;
import admin.forms.CategoryForm;

public class AddCategoryServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		TreeMap check = new TreeMap();
		CategoryData cData = new CategoryData();
		ArrayList<CategoryModel> categories = cData.listAll();
		CategoryModel category = new CategoryModel();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("category", category);
		request.setAttribute("categories", categories);
		request.setAttribute("hasChildren", false);
		try {
			request.getRequestDispatcher("/admin/pages/form_category.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		CategoryData cData = new CategoryData();
		CategoryModel category = new CategoryModel();
		
		//Check valid and get value form
		CategoryForm cForm = new CategoryForm();
		TreeMap forms = cForm.checkValid(request, category);
		category = (CategoryModel) forms.get("category");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if (check.size() == 0)
        {
			cData.insert(category);
			request.setAttribute("success", "Add success category " + category.getId());
			category = new CategoryModel();
        }
		
		ArrayList<CategoryModel> categories = cData.list();
		
		request.setAttribute("check", check);
		request.setAttribute("categories", categories);
		request.setAttribute("category", category);
		request.setAttribute("hasChildren", false);
		request.setAttribute("form", "add");
		try {
			request.getRequestDispatcher("/admin/pages/form_category.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
